说起左侧固定,右侧自适应;或者左右固定,中间自适应,大家想到的可能最多的就是通过 flex 弹性盒布局中的 flex:1 吧,那么 flex:1 究竟是什么呢?
flex 属性是 flex-grow, flex-shrink 和 flex-basis 的简写,默认值为 0 1 auto(后两个属性可选)
- auto (1 1 auto) 和 none (0 0 auto)
- flex: 1, 对应的是 1 1 0%
- flex: 0, 对应的是 0 1 0%
flex: 1 不管内容多少,一般都是平分空间,空间大小都一致
而flex: auto是根据内容的大小来分,不是均分的(除非内容都是一样,才均分)
flex: 0 不可扩大,可缩小,表现形式为最小内容宽度, 上图你可以看到div的宽度就是一个字的宽度
flex: none 可扩大,不可缩小,内容本身的宽度是多少就是多少
而flex: none 不可扩大,不可缩小,内容本身的宽度是多少就是多少那么这三个属性对应的功能又是什么呢?
MDN 介绍:flex - CSS(层叠样式表) | MDN
flex-grow
代表子元素占弹性盒子的比例
<!-- HTML部分 -->
<div class="grow">
<!-- flex-grow占用父元素的比例 -->
<div class="grow-child1">flex-grow: 2</div>
<div class="grow-child2">flex-grow: 6</div>
</div>
/* css部分 */
.grow {
width: 800px;
height: 200px;
background-color: aqua;
display: flex;
}
.grow-child1 {
flex-grow: 2;
background-color: red;
}
.grow-child2 {
flex-grow: 6;
background-color: royalblue;
}效果图:
此时,红色部分和蓝色部分的比例为 2:6,也就是分别为 200px 和 800px
flex-shrink
子元素超出父元素宽度后,对应每个子元素的收缩规则
如下代码,超出部分为(800+800-800)px,也就是 800px,所以 child2 为例,超出部分的收缩规则为 800 * 3/(1+3))= 600px,所以 child2 应收缩 600px,所以当前 child2 的宽度为 800-600px = 200px
<!-- HTML部分 -->
<div class="shrink">
<div class="shrink-child1">shrink-child1</div>
<div class="shrink-child2">shrink-child2</div>
</div>
<hr />
/* css部分 */
.shrink {
width: 800px;
height: 200px;
background-color: aqua;
display: flex;
}
.shrink-child1 {
width: 800px;
flex-shrink: 1;
background-color: red;
}
.shrink-child2 {
width: 800px;
flex-shrink: 3;
background-color: royalblue;
}效果图
flex-basis
当前子弹性盒的尺寸
<!-- HTML部分 -->
<div class="basis">
<div class="basis-child1">basis-child1</div>
<div class="basis-child2">basis-child2</div>
</div>
<hr />
/* css部分 */
.basis {
width: 800px;
height: 200px;
background-color: aqua;
display: flex;
}
.basis-child1 {
flex-basis: 80%;
background-color: red;
}
.basis-child2 {
width: 100px;
background-color: royalblue;
}效果图
(最右侧的是 basis 盒子的颜色,当前 child1 宽度为 800 * 0.8 = 640px,child2 的宽度为 100px,所以 child1+child2 < 盒子宽度,所以底层盒子没有填满)
flex 1
自动填充满剩余空间,如果有两个地方设置了 flex,按着 flex-grow 的规则分配剩余空间
假设一个 flex 弹性盒中有三个子元素,child1,child2 分别设置了 flex:1,flex2,child1 宽度固定为 200px,那么现在 child1 的宽度为 200px,child2 的宽度为 600px,child 的宽度不变还是 200px
<!-- HTML部分 -->
<div class="flex">
<div class="flex-child1">flex-child1</div>
<div class="flex-child2">flex-child3</div>
<div class="flex-child3">flex-child3</div>
</div>
/* css部分 */
.flex {
width: 800px;
height: 200px;
background-color: aqua;
display: flex;
}
.flex-child1 {
flex: 1;
background-color: red;
}
.flex-child2 {
flex: 2;
/* width: 100px; */
background-color: royalblue;
}
.flex-child3 {
width: 200px;
background-color: sandybrown;
}效果图
有两个地方设置了 flex,按着 flex-grow 的规则分配剩余空间,此时 child1 为 200px,child2 为 400px
注意: 此代码中被注释的 width 属性,如果同时存在 flex:1 和 width 属性,则优先使用 flex1,即 flex:1优先级大于width
转载
你了解flex: 1,flex: auto,flex: 0,flex: none的区别吗?